import React, { useRef } from 'react';
import { addFloorAPI } from '@/api/floor.api';
import { FormInstanceFunctions } from 'tdesign-react/es/form/type';
import { Dialog, Form, Input, Button, MessagePlugin, Space } from 'tdesign-react';
import { IFloorFormProps, FLOOR_FORM_RULES, IFloorForm, IApiResponse } from '../consts';

const { FormItem } = Form;

const FloorForm: React.FC<IFloorFormProps> = ({ visible, onClose, onSuccess }) => {
  const formRef = useRef<FormInstanceFunctions>();

  const handleSubmit = async () => {
    const valid = await formRef.current?.validate();
    if (valid === true) {
      try {
        const values = formRef.current?.getFieldsValue(true) as IFloorForm;
        if (!values) {
          MessagePlugin.error('请输入楼层号和描述');
          return;
        }
        const res = await addFloorAPI({
          floorNumber: Number(values.floorNumber),
          description: values.description,
        }) as IApiResponse<any>;

        if (res.status === 201) {
          MessagePlugin.success(res.data?.message || '添加成功');
          formRef.current?.reset();
          onSuccess();
          onClose();
        } else {
          MessagePlugin.error(res.data?.message || '添加失败');
        }
      } catch (error: any) {
        MessagePlugin.error(error.response?.data?.message || '添加失败');
      }
    }
  };

  return (
    <Dialog
      header="新建楼层"
      visible={visible}
      onClose={onClose}
      footer={
        <Space>
          <Button theme="default" onClick={onClose}>
            取消
          </Button>
          <Button theme="primary" onClick={handleSubmit}>
            确定
          </Button>
        </Space>
      }
    >
      <Form ref={formRef} labelWidth={100} rules={FLOOR_FORM_RULES}>
        <FormItem label="楼层号" name="floorNumber">
          <Input placeholder="请输入楼层号，例如：1" />
        </FormItem>
        <FormItem label="描述" name="description">
          <Input placeholder="请输入描述" />
        </FormItem>
      </Form>
    </Dialog>
  );
};

export default FloorForm; 